#include "ring_node.h"

#define MAX_STRING 100

void ring_node(int node_id, int nb_messages){

  int pid = obtenir_pid();
  int parent_pid = obtenir_parent(pid);
  int next_node_pid;
  int message_number = 1;
  char i[4], n_id[4];
  char buf[MAX_STRING], s[MAX_STRING];
  /* get next ring nodes id from parent */
  message_t m;
  recevoir_de(parent_pid,&m);
  next_node_pid = message_get_int_value(m);

  itoa(node_id,n_id,4);

  while (message_number <= nb_messages) {
    /* if we are the "last" node in the ring (the next node has
     * a smaller pid than us) we control the messages. That means
     * we create the first ones and are the last to receive. */
    /* If messages were already sent, we have to receive */
    recevoir_premier(&m);
    if (pid > next_node_pid) {
      if (message_number == 1) {
        ecrire("Will start sending messages.\n");
      } else {
        strncpy(buf,"Process ", MAX_STRING);
        strncat(buf,n_id,MAX_STRING-strlen(buf));
        strncat(buf,": message went through ring: \"",MAX_STRING-strlen(buf));
        strncat(buf,message_get_str_value(m), MAX_STRING-strlen(buf)-2);
        strncat(buf,"\"\n", MAX_STRING-strlen(buf));
        ecrire(buf);
      }
      liberer_message(m); //not needed anymore
      strncpy(s, "Message number ", MAX_STRING);
      itoa(message_number, i, 4);
      strncat(s, i, MAX_STRING-strlen(s));
      strncpy(buf,"Process ",MAX_STRING);
      strncat(buf,n_id,MAX_STRING-strlen(buf));
      strncat(buf," inserted message into ring: ", MAX_STRING-strlen(buf));
      strncat(buf,s,MAX_STRING-strlen(buf)-1);
      strncat(buf,"\n",MAX_STRING-strlen(buf));
      ecrire(buf);
      retarder(pid, 3000);
      if(envoyer_chaine(next_node_pid, s, 9) == OUT_OF_MEMORY){
        ecrire("Out of memory\n");
        quitter(FAILURE);
      }
      message_number++;
      /* We are not the controlling node, just receive and send forth */
    } else {
      strncpy(buf,"Node number ", MAX_STRING);
      strncat(buf,n_id, MAX_STRING-strlen(buf));
      strncat(buf," received: \"",MAX_STRING-strlen(buf));
      strncat(buf,message_get_str_value(m), MAX_STRING-strlen(buf)-2);
      strncat(buf,"\"\n", MAX_STRING-strlen(buf));
      ecrire(buf);
      retarder(pid, 3000);
      if(envoyer_chaine(next_node_pid, message_get_str_value(m), 9) == OUT_OF_MEMORY){
        ecrire("Out of memory\n");
        quitter(FAILURE);
      }
      liberer_message(m);
      message_number++;
    }
  }
  /* get the last message and finish up */
  if (pid > next_node_pid) {
    recevoir_premier(&m);
    ecrire("Process ");
    ecrire(n_id);
    ecrire(": message went through ring: \"");
    ecrire(message_get_str_value(m));
    ecrire("\"\n");
    ecrire("All messages sent through ring...\n");
    liberer_message(m);
  }
  quitter(SUCCESS);
}
